<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button
      v-if="draggable"
      @click="dragBatchSave"
      type="primary"
      size="mini"
      round
      >拖拽保存</el-button
    >
    <el-button type="danger" size="mini" @click="batchDelete" round
      >批量删除</el-button
    >
    <el-tree
      :data="categories"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="categoryTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="edit(data)">
            Edit
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      categories: [], //分类数据
      expandedKey: [], //默认展开的key值
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogVisible: false, //不显示
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        productUnit: "",
        icon: "",
      }, //添加分类时，表单对象
      dialogType: "", //对话框类型：edit,add
      title: "", //提示框title
      maxLevel: 0, //定义最大层级（拖拽节点时，统计子节点最大深度catLevel）
      updateNodes: [], //拖拽后需要更新的节点数据
      draggable: false, //Tree树形控件是否能拖拽
      pCid: [], //拖拽完成后需要展开的父分类id
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    //获取所有分类列表
    getCategories() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        //注意这里的{data}用了对象的解构
        console.log("成功获取到菜单数据：", data.data);
        this.categories = data.data;
      });
    },

    //打开新增分类对话框
    append(data) {
      console.log("append...", data);
      //设置对话框类型
      this.dialogType = "add";
      //设置对话框title
      this.title = "新增分类";
      //打开对话框
      this.dialogVisible = true;
      //新增分类初始化值
      this.category.name = ""; //分类名称清空
      this.category.parentCid = data.catId; //设置新增分类的父id
      this.category.catLevel = data.catLevel * 1 + 1; //*1是为了避免是字符串转化成数字，+1就是当前分类级别加1

      this.category.catId = null;
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
      this.category.showStatus = 1;
    },

    //提交分类数据
    submitData() {
      console.log("提交的三级分类数据", this.category);

      if (this.dialogType == "add") {
        //新增分类
        this.addCategory();
      } else if (this.dialogType == "edit") {
        //编辑分类
        this.editCategory();
      }
    },

    //新增三级分类
    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$message({
          message: "添加分类成功",
          type: "success",
        });

        //关闭对话框
        this.dialogVisible = false;

        //设置需要默认展开的分类
        this.expandedKey = [this.category.parentCid];
        this.getCategories(); //刷新分类列表
      });
    },

    //打开编辑分类对话框
    edit(data) {
      console.log("要修改的数据...", data);
      //设置对话框类型
      this.dialogType = "edit";
      //设置对话框title
      this.title = "编辑分类";
      //打开对话框
      this.dialogVisible = true;
      //发送请求获取当前节点最新的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        //请求成功
        //回显数据
        console.log("要回显的数据...", data);
        this.category.name = data.data.name; //回显分类名称
        this.category.catId = data.data.catId; //传回当前分类id
        this.category.icon = data.data.icon; //回显图标
        this.category.productUnit = data.data.productUnit; //回显计量单位
        this.category.parentCid = data.data.parentCid; //回显父菜单id
      });
    },
    //编辑三级分类
    editCategory() {
      //重整数据，哪些数据需要更改的
      var { catId, name, icon, productUnit } = this.category; //对象解构
      // var data = {catId:catId, name:name, icon:icon, productUnit:productUnit};//同下，key值和value变量名一样则可以省略
      var data = { catId, name, icon, productUnit };
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(data, false),
      }).then(({ data }) => {
        this.$message({
          message: "修改分类成功",
          type: "success",
        });

        //关闭对话框
        this.dialogVisible = false;

        //设置需要默认展开的分类
        this.expandedKey = [this.category.parentCid];
        this.getCategories(); //刷新分类列表
      });
    },

    //删除分类
    remove(node, data) {
      var ids = [data.catId];
      console.log("remove...", node, data);

      this.$confirm(`是否删除【${data.name}】分类?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              message: "删除分类成功",
              type: "success",
            });
            this.getCategories(); //刷新分类列表
            //设置需要默认展开的分类
            this.expandedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    allowDrop(draggingNode, dropNode, type) {
      console.log(draggingNode, dropNode, type);
      //1.被拖动的当前节点以及所在的父节点总层数不能大于3
      //1.1被拖动的当前节点总层数
      this.countNodeLevel(draggingNode);

      console.log("拖拽节点里的最大层级数：", this.maxLevel);
      let deep = this.maxLevel - draggingNode.level + 1;
      console.log("拖拽节点的最大深度：", deep);
      if (type == "inner") {
        //拖拽到目标节点内
        return deep + dropNode.level <= 3;
      } else if (type == "prev" || type == "next") {
        //拖拽到目标节点前prev,后next
        return deep + dropNode.parent.level <= 3;
      }
    },
    //计算节点最大level
    countNodeLevel(node) {
      //找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        //当前节点有子节点
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]); //递归查询
        }
      } else {
        this.maxLevel = node.level;
      }
    },

    //拖拽成功后
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", draggingNode, dropNode, dropType, ev);

      //1.当前拖拽节点最新的父节点id
      let pCid = 0;
      let siblings = null; //当前拖拽节点拖到目标节点后的兄弟
      if (dropType == "inner") {
        //当前拖拽的节点在目标节点内
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      } else if (dropType == "before" || dropType == "after") {
        //当前拖拽的节点在目标节点前或后dropType == "after" 或者 "before"
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }
      this.pCid.push(pCid); //存放拖拽完成后需要展开的父节点

      console.log("siblings...", siblings);

      //2.当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (draggingNode.data.catId == siblings[i].data.catId) {
          let currentCatLevel = draggingNode.level; //保存拖拽节点原始层级
          if (draggingNode.level != siblings[i].level) {
            //如果当前拖拽节点的层级发生了变化
            //更新当前拖拽节点的层级
            currentCatLevel = siblings[i].level;

            //更新当前拖拽节点的子节点的层级
            this.updateChildNodesCatLevel(siblings[i].childNodes);
          }

          //如果目前遍历的就是当前拖拽的节点，则需要额外更改父id
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: currentCatLevel,
          });
        } else {
          //只更改其它兄弟节点的顺序
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }

      //3.当前拖拽节点的最新层级level，在步骤2中已完成

      console.log("updateNodes...", this.updateNodes);
    },

    //更新当前拖拽节点的子节点的层级
    updateChildNodesCatLevel(nodes) {
      for (let i = 0; i < nodes.length; i++) {
        this.updateNodes.push({
          catId: nodes[i].data.catId,
          catLevel: nodes[i].level,
        });

        //递归，更新其子节点
        this.updateChildNodesCatLevel(nodes[i].childNodes);
      }
    },

    //拖拽批量保存
    dragBatchSave() {
      if (this.updateNodes.length == 0) {
        return;
      }
      //发送请求更新数据
      this.$http({
        url: this.$http.adornUrl("/product/category/updateBatch"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          message: "分类顺序修改成功",
          type: "success",
        });
        this.getCategories(); //刷新分类列表

        //设置需要默认展开的分类
        this.expandedKey = this.pCid;
        console.log("展开的分类：", this.pCid);
        //清空数据，为下次拖拽做准备
        this.updateNodes = []; //清空需要更新的节点数据
        this.maxLevel = 0; //清空拖拽的子节点最大catLevel
        this.pCid = []; //保存完成后，清空拖拽完成后需要展开的父分类id
      });
    },

    //批量删除分类
    batchDelete() {
      let catIds = [];
      let catNames = [];
      let checkedNodes = this.$refs.categoryTree.getCheckedNodes();
      console.log("被选中的节点:", checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId);
        catNames.push(checkedNodes[i].name);
      }
      if (catIds.length == 0) {
        return;
      }

      this.$confirm(`是否批量删除【${catNames}】分类?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            this.$message({
              message: "批量删除分类成功",
              type: "success",
            });
            this.getCategories(); //刷新分类列表
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getCategories();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped>
</style>